package ${(projectConfig.projectPackageName)!}.common.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private CustomUserDetailsService customUserDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    public CustomAuthenticationProvider() {
        super();
    }

    @Override
    public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
        final String username = authentication.getName();
        final String password = authentication.getCredentials().toString();

        if((StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
            <#if "${(dependencies.weixin)!}" != ""> && StringUtils.isEmpty(wxCode)</#if>) {
            throw new BadCredentialsException("invalid params: username,password<#if "${(dependencies.weixin)!}" != ""> and wxCode are</#if> invalid");
        }

        UserDetails userDetails = null;
        if(!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            try {
                userDetails = customUserDetailsService.loadUserByUsername(username);

                if(userDetails == null || userDetails.getPassword() == null) {
                    throw new BadCredentialsException("invalid password");
                }
                if(!passwordEncoder.matches(password, userDetails.getPassword())) {
                    throw new BadCredentialsException("wrong password");
                }
            } catch (UsernameNotFoundException e) {
                e.printStackTrace();
            }
        }

        <#if "${(dependencies.weixin)!}" != "">
        if(userDetails == null) {
            CustomWebAuthenticationDetails details = (CustomWebAuthenticationDetails) authentication.getDetails();
            final String wxCode = details.getWxCode();
            if(!StringUtils.isEmpty(wxCode)) {
                String openid = tokenManager.getOpenid(wxCode);
                principal = customUserDetailsService.loadUserByOpenid(openid);
            }
        }
        </#if>

        if(userDetails != null) {
            final List<GrantedAuthority> grantedAuths = (List<GrantedAuthority>) userDetails.getAuthorities();
            final Authentication auth = new UsernamePasswordAuthenticationToken(userDetails, password, grantedAuths);
            return auth;
        }

        return null;
    }

    @Override
    public boolean supports(final Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}